package com.sk.places.places2.business.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.omg.CORBA.NameValuePair;

import com.sk.places.places2.service.entity.Place;
import com.sk.places.places2.service.entity.PlaceType;

/**
 * Service to get {@link Place} by various combinations
 * @author skhurana
 *
 */
public class PlaceServiceImpl implements PlaceService{

	@PersistenceContext(name="")
	private EntityManager em; 
	private Logger logger = Logger.getLogger("PlaceServiceImpl") ;
	
	/**
	 * Will get all the {@link Place} places
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Place> getAllPlaces() {
		Query qry = em.createQuery(" select p from Place p") ;
		return qry.getResultList() ;
	}

	/**
	 * Will get the {@link Place} objects by type and visiting month
	 */
	@SuppressWarnings({ "unchecked"})
	@Override
	public List<Place> getPlacesByTypeAndVistingMonth(List<Long> types, String visitingMonth) {
		if( ( types == null  || types.isEmpty()) || ( visitingMonth == null || visitingMonth.isEmpty()) ) return getAllPlaces() ; 
		
		StringBuilder strQry =  new StringBuilder("Select p from Place p left join p.placeTypes pt left join p.placeTravel ptravel  where ");
		strQry.append("pTravel.bestMonthFrom<=convert(?1, unsigned) and pTravel.bestMonthTo>=convert(?2, unsigned) or pTravel.bestMonthFrom>=convert(?1, unsigned) and pTravel.bestMonthTo<=convert(?2, unsigned)");
		//strQry.append(" and " + types!= null?" pt.id  IN (?3) ":""  ); 
		System.out.println("strQry+++++++++ : "  + strQry);
		System.out.println("visitingMonth : "  +visitingMonth);
		
		Query qry = em.createQuery(strQry.toString()) ;
		/*Map<String, Object> params = new HashMap<String, Object>();
		params.put("tp", types);*/
		qry.setParameter(1, visitingMonth);
		qry.setParameter(2,visitingMonth);
		//qry.setParameter(3, types);
		logger.info(" qry is " + qry.toString()) ;
		
		return qry.getResultList() ;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<PlaceType> getPlacesTypes() {
		Query qry = em.createQuery("Select pt from PlaceType pt order by pt.placeType")  ;
		logger.info(qry.toString());
		return qry.getResultList();
	}	

	
	public EntityManager getEm() {
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}


}
